package cn.itcast.flink.keyedstate;

import org.apache.commons.io.FileUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Author itcast
 * Date 2022/1/16 11:27
 * Desc 每 2s 读取文件中的每行数据，现在对每行进行单词的拆分
 * 通过 flatMap 进行单词的统计，中间结果状态保存的 TTL 时间是 7s
 */
public class WordcountTTLState {
    public static void main(String[] args) throws Exception {
        //todo 1.创建流执行环境，设置并行度
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //todo 2.设置checkpoint，设置1s，设置状态后端在本地任意目录
        env.enableCheckpointing(1000);
        //todo 3.添加数据源，自定义数据源 SourceFunction ，每 2s 读取一行
        DataStreamSource<String> source = env.addSource(new SourceFunction<String>() {
            volatile boolean isRunning = true;

            @Override
            public void run(SourceContext<String> ctx) throws Exception {
                while (isRunning) {
                    List<String> lines = FileUtils.readLines(
                            new File("D:\\project\\flinkbase27\\data\\words.txt")
                            , "utf-8"
                    );
                    for (String line : lines) {
                        ctx.collect(line);
                        TimeUnit.SECONDS.sleep(3);
                    }
                }
            }

            @Override
            public void cancel() {
                isRunning = false;
            }
        });
        //todo 4.将每个单词转换成 Tuple2<String，Integer>
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = source.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        })
                //todo 5.根据单词进行分组
                .keyBy(t -> t.f0);
        //todo 6.将数据流进行flatMap用于设置保存中间结果state到ValueState及TTL，存活时间7s，flatMap实现元素和状态的累加
        keyedStream.flatMap(new RichFlatMapFunction<Tuple2<String, Integer>, Tuple2<String,Integer>>() {
            //实现获取当前的变量 state
            ValueState<Tuple2<String, Integer>> state = null;
            @Override
            public void open(Configuration parameters) throws Exception {
                //获取 Tuple2 描述器
                ValueStateDescriptor<Tuple2<String,Integer>> reduceStateDesc =
                        new ValueStateDescriptor<>("reduceState", Types.TUPLE(Types.STRING, Types.INT));
                //设置 state TTL 生命周期
                StateTtlConfig config = StateTtlConfig
                        //实例化间隔 7s state状态过去
                        .newBuilder(Time.seconds(4))
                        //设置过期不再返回
                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                        //设置创建和更新state内容的更新时间戳
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        //设置 ttl 时间属性为processingTime 这个是默认时间戳
                        .setTtlTimeCharacteristic(StateTtlConfig.TtlTimeCharacteristic.ProcessingTime)
                        .build();
                //将 TTL 设置 state
                reduceStateDesc.enableTimeToLive(config);
                //获取 state
                state = getRuntimeContext().getState(reduceStateDesc);
            }

            //实现累加操作
            @Override
            public void flatMap(Tuple2<String, Integer> value, Collector<Tuple2<String, Integer>> out) throws Exception {
                //数据的累加操作
                Tuple2<String, Integer> reduce = state.value();
                if(reduce == null){
                    reduce = value;
                    out.collect(reduce);
                    state.update(reduce);
                }else{
                    //聚合结果
                    Tuple2<String, Integer> result = Tuple2.of(value.f0, value.f1 + reduce.f1);
                    state.update(result);
                    out.collect(result);
                }
            }

        })
        //todo 7.打印输出
        .print();
        //todo 8.执行流环境
        env.execute();

        //todo 继承RichSourceFunction用于按行读取数据
        //创建读取文件中的数据，任意
        //重写run方法，每5s读取文件中的一行数据
        //重写cancel方法
    }
}
